<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { productAdd, productInfo, productUpdate } from '#/api/hm/product';
import { deptList } from '#/api/system/dept';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 80,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await productInfo(id);
      // 将后端返回的 isCommercialProduct 和 isGiftProduct 转换为前端 CheckboxGroup 期望的数组格式
      const productTypesSelected = [];
      if (record.isCommercialProduct) {
        productTypesSelected.push('CP');
      }
      if (record.isGiftProduct) {
        productTypesSelected.push('ZP');
      }
      await formApi.setValues({ ...record, productTypesSelected }); // 设置表单值，包括新的 productTypesSelected
    } else {
      // 新增时，设置默认值，例如默认选中商品产品
      await formApi.setValues({ productTypesSelected: ['CP'] });
    }

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());

    // 根据 productTypesSelected 数组设置 isCommercialProduct 和 isGiftProduct
    data.isCommercialProduct = data.productTypesSelected.includes('CP');
    data.isGiftProduct = data.productTypesSelected.includes('ZP');
    delete data.productTypesSelected; // 移除前端临时字段

    // 移除旧的 productType 字段，如果它仍然存在于 data 中
    // delete data.productType; // 如果后端不再使用此字段，可以删除

    await (isUpdate.value ? productUpdate(data) : productAdd(data));
    emit('reload');
    await handleCancel();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  await formApi.resetForm();
}

const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin', 'ceo']);
});
// 获取服务店铺列表
onMounted(async () => {
  const requestParams = { ancestors: '101', deptCategory: 'DP' };
  if (isAdmin.value) {
    requestParams.deptCategory = '';
  }
  const deptTree = await deptList(requestParams);
  const deptOptions = [];
  const deptTransOptions = deptTree.map((item) => ({
    label: item.deptName,
    value: item.deptId,
  }));
  deptOptions.push(...deptTransOptions);
  // 选中后显示在输入框的值 即父节点 / 子节点
  // ddFullName(deptTree, 'label', ' / ');
  formApi.updateSchema([
    {
      fieldName: 'shopSale',
      componentProps: {
        options: deptOptions,
        showSearch: true,
        optionFilterProp: 'label',
        // fieldNames: { label: 'label', value: 'id' },
        // treeData: deptTree,
        // // 选中后显示在输入框的值
        // treeNodeLabelProp: 'fullName',
        // treeDefaultExpandAll: true,
        // treeLine: { showLeafIcon: false },
      },
    },
  ]);
});
</script>

<template>
  <BasicModal :close-on-click-modal="false" :title="title" class="w-[550px]">
    <BasicForm />
  </BasicModal>
</template>
